package com.yhb.service;

import com.alipay.api.internal.util.file.FileUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yhb.model.config.feeRate.FeeRateChannel;
import lombok.extern.log4j.Log4j;
import lombok.var;
import me.edzh.spring.bootstrap.utils.JSONUtil;
import me.edzh.spring.bootstrap.utils.MathUtils;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Log4j
@Service
public class GenIPService {
    private volatile Map<String, List<String>> geoIPRanges;

    public synchronized void updateRanges(String yamlString) {
        var yaml = new Yaml();
        var res = yaml.loadAs(yamlString, Map.class);

        this.geoIPRanges = JSONUtil.parseJson(res, new TypeReference<Map<String, List<String>>>() {});

        log.info("geoip updated, total geo points:" + this.geoIPRanges.size());
    }

    public String randomIPOfPlace(String province, String city) {
        var ip = randomIPOfKey(city);
        if (ip == null) {
            return randomIPOfKey(province);
        } else {
            return ip;
        }

    }

    public String randomIPOfKey(String key) {
        var list = geoIPRanges.get(key);
        if (list == null) {
            return null;
        }

        String pattern = list.get(MathUtils.random(0, list.size() - 1));
        pattern = pattern.replace("{A}", String.valueOf(MathUtils.random(0, 255)));
        pattern = pattern.replace("{B}", String.valueOf(MathUtils.random(0, 255)));
        pattern = pattern.replace("{C}", String.valueOf(MathUtils.random(0, 255)));
        pattern = pattern.replace("{D}", String.valueOf(MathUtils.random(0, 255)));

        return pattern;
    }

    public static void main(String[] args) throws IOException {
        var s = new GenIPService();
        s.updateRanges(FileUtils.readFileToString(new File("/Users/edwardzhou/Documents/codes/yhb/new/api_server/deploy/runtime_dependencies/config/geoIPs.yaml"), StandardCharsets.UTF_8));
        System.out.println(s.randomIPOfPlace("浙江省", "温州市"));
    }
}
